package com.yadang.csv;

/**
 * @author: 亚当
 * @date: 2023年05月16日 23:17
 * @package: com.yadang.csv
 * @Description: TODO
 */
import com.opencsv.CSVWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
// openCSV
public class ExportToCSV1 {

    public static void main(String[] args) {
        User user = new User();
        user.setUserName("张三");
        user.setSex("男");
        user.setAge(28);
        List<User> list = new LinkedList<>();
        list.add(user);
        String fileName = "D:\\11234.tmp";
        File oldFileName = new File(fileName);
        exportListToCSV(list, fileName);
        File newFileName = new File("D:\\11234.csv");
        oldFileName.renameTo(newFileName);

    }

    public static void exportListToCSV(List<User> userList, String csvFileName) {
        try (
                FileOutputStream fos = new FileOutputStream(csvFileName);
                OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
                CSVWriter csvWriter = new CSVWriter(osw,
                        CSVWriter.DEFAULT_SEPARATOR,
                        CSVWriter.NO_QUOTE_CHARACTER,
                        CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                        CSVWriter.DEFAULT_LINE_END)
        ) {
            // Write BOM to support Chinese characters in Excel
            fos.write(0xEF);
            fos.write(0xBB);
            fos.write(0xBF);

            // Write header
            String[] header = {"姓名", "性别", "年龄"};
            csvWriter.writeNext(header);

            // Write data
            for (User user : userList) {
                String[] userData = {user.getUserName(), user.getSex(), String.valueOf(user.getAge())};
                csvWriter.writeNext(userData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
